package com.hd123.rumba.gwt.widget.client.codenamebox;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.PopupListener;
import com.google.gwt.user.client.ui.PopupPanel;
import com.hd123.rumba.gwt.widget.client.Util;

public abstract class CNBAbstractListener implements CNBListener, PopupListener {
  public abstract void findByCode(AsyncCallback callback);

  public abstract CNBBrowserDataProvider createBrowserDataProvider();

  public CodeNameBox codeNameBox;
  private AsyncCallback findCallback = null;
  private CNBBrowser browser = null;
  private CNBBrowserDataProvider browserDataProvider = null;

  public CNBFilter getFilter() {
    return browserDataProvider == null ? null : browserDataProvider.getFilter();
  }

  public void onCodeChanged(final CodeNameBox codeNameBox) {
    this.codeNameBox = codeNameBox;
    codeNameBox.setUserDataUuid(null);
    codeNameBox.setName("请稍候...");
    if (findCallback == null) {
      findCallback = new AsyncCallback() {

        public void onFailure(Throwable caught) {
          Util.showErrorDialog(caught.getMessage());
        }

        public void onSuccess(Object result) {
          UuidCodeName vo = (UuidCodeName) result;
          codeNameBox.setUuidCodeName(vo);
          if (vo.getUuid() == null) {
            codeNameBox.setNameErrorText("没有找到");
          }
          codeNameBox.fireChange();
        }

      };

    }
    findByCode(findCallback);
  }

  public void onSearchStart(CodeNameBox codeNameBox) {
    this.codeNameBox = codeNameBox;
    if (browserDataProvider == null) {
      browserDataProvider = createBrowserDataProvider();
    }
    if (browser == null) {
      browser = new CNBBrowser(browserDataProvider);
      browser.addPopupListener(this);
    }
    browser.setPopupPosition(codeNameBox.getAbsoluteLeft(), codeNameBox.getAbsoluteTop()
        + codeNameBox.getOffsetHeight());
    browser.show();
  }

  public void onPopupClosed(PopupPanel sender, boolean autoClosed) {
    if (sender == browser && !autoClosed) {
      if (browser.selectedObject != null) {
        codeNameBox.setUuidCodeName((UuidCodeName) browser.selectedObject);
        codeNameBox.fireChange();
      }
      Util.focusTextBox(codeNameBox.getCodeBox());
    }
  }

}
